class TodoItem < ActiveRecord::Base
  belongs_to :todo
  belongs_to :user
  after_create :save_log
  after_update :update_log
def save_log
  if self.user
  Log.info(self.todo.project,
       "<a href=/projects/#{self.todo.project.id}/todos>#{self.name}</a>",
       8,
       "Assigned to",
       self.user
    )
  else
  Log.info(self.todo.project,
       "<a href=/projects/#{self.todo.project.id}/todos>#{self.name}</a>",
       8,
       "Posted by",
       Thread.current[:user]
    )
  end
end

def update_log
  if self.finished_at.to_i > 0
  Log.info(self.todo.project,
       "<a href=/projects/#{self.todo.project.id}/todos/#{self.todo.id}><s>#{self.name}</s></a>",
       8,
       "Finished by",
       Thread.current[:user]
    )
  elsif self.finished_at.to_i == 0
  Log.find(:first,:conditions=>["project_id = ? and name = ? and type_id=? and label=? and user_id = ?",
       self.todo.project.id,
       "<a href=/projects/#{self.todo.project.id}/todos/#{self.todo.id}><s>#{self.name}</s></a>",
       8, 
       "Finished by",
       Thread.current[:user].id
       ]).destroy
  end
end
def started_at
  if self.start_at and self.start_at > self.todo.started_at
    return self.start_at
  elsif self.todo.started_at
    return self.todo.started_at
  elsif not self.todo.milestone.nil?
    if not self.todo.milestone.start_at.nil?
      return self.todo.milestone.start_at
    elsif not self.todo.milestone.created_at.nil?
      return self.todo.milestone.created_at
    end 
  elsif self.created_at
    return self.created_at
  else
    return self.todo.project.add_at
  end
end
def ended_at
  if self.finished_at.to_i > 0
    return self.finished_at
  elsif self.due_at 
    if self.todo.due_at and self.due_at < self.todo.due_at
    return self.due_at
    else
    return self.todo.due_at
    end
  else
    return nil
  end
end
end
